#include <semaphore.h>
#include <stdio.h>
#include <pthread.h>

#define N 10
#define M 8

sem_t space, prod, sin, sout;

int Buffer[N];   
int in=0, out =0; 

void * producer(void *p){
    while(1){
        sem_wait(&space);
        sem_wait(&sin);
        printf("Put a product into Buffer[%d]!\n", in);
        in = (in +1)%N; 
        sem_post(&prod);
        sem_post(&sin);
    } 
    return NULL;
}

void * consumer(void *p){
    while(1){
        sem_wait(&prod);
        sem_wait(&sout);
        printf ("Get a product from Buffer[%d]!\n", out);
        out = (out +1)%N; 
        sem_post(&space);
        sem_post(&sout);
     }  
     return NULL;
}


int main(void)
{ 
    sem_init(&space, 0, N); 
    sem_init(&prod, 0, 0);
    sem_init(&sin, 0, 1);       
    sem_init(&sout, 0, 1);
    pthread_t tid[M], tid2[M];
    for(int i=0; i<M; i++) 
        pthread_create(&tid[i], NULL, producer, NULL);
    for(int i=0; i<M; i++) 
        pthread_create(&tid2[i], NULL, consumer, NULL);
    sem_destroy(&space); 
    pthread_join(tid[M-1], NULL);
}